import React from 'react';
import { connect, routerRedux } from 'dva';
import moment from 'moment';
import { getUserInfo, isZiGuanEvir } from '../../../utils/commonFunc';
import { AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, FirstHeaderC, ContentPackage } from '../../../comps';
import config from '../../../comps/business/searchAndSelect/enum';
import BaseInfoForm from './baseInfoForm'; // 这个是表单的页面
// eslint-disable-next-line import/imports-first
import { message } from 'antd';
import MyModalC from './myModalC';
import { findTitleByValue } from '../../../utils/utils';
import styles from './index.less';
// eslint-disable-next-line import/imports-first

class ProductManage extends React.Component {
  constructor() {
    super();
    this.state = {
      pageStatus: '1', // 当前所在页面  1是列表页面  2是表单页面
      isReset: false,
      searchParam: {},
      formDatas: {
        baseInfo: {}, // 基本信息
      },
      pageInfo: {
        numInPage: 10,
        currentPage: 1,
        total: 0,
      },
      dataSource: [],
      columns: [
        { dataIndex: 'productName', title: '产品名称', key: 'productName' },
        { dataIndex: 'productSimpleName', title: '产品简称', key: 'productSimpleName' },
        { dataIndex: 'code', title: '估值代码', key: 'code' },
        { dataIndex: 'productStatus', title: '产品状态', key: 'productStatus' },
        { dataIndex: 'startDate', title: '成立日', key: 'startDate' },
        { dataIndex: 'endDate', title: '到期日', key: 'endDate' },
        { dataIndex: 'productType', title: '产品类型', key: 'productType' },
        { dataIndex: 'inveType', title: '投资类型', key: 'inveType' },
        { dataIndex: 'modes', title: '交易模式', key: 'modes' },
        { dataIndex: 'baxx_cpmjfs', title: '募集方式', key: 'baxx_cpmjfs' },
        { dataIndex: 'limits', title: '产品期限', key: 'limits' },
        { dataIndex: 'productWorkType', title: '运作模式', key: 'productWorkType' },
      ],
      pageType: '', // 表单页面的状态，如果是新增则是add  编辑是edit  查看是view
      productId: '',
      parentRefsWidth: 0,
      visible: false, // 弹窗是否可见
      record: undefined, // 当前行的数据
      modeType: '0', // 估值/手工录入区分标志位，modeType，0-新增，1-估值，2-手工录入
      sortedInfo: null, // 排序对象
    };
  }

  componentDidMount() {
    // 查询数据字典
    const {
      globalM: { dataDictionary = {} },
    } = this.props;
    this.props.dispatch({
      type: 'productManageM/fetchDictByKeys',
      payload: {
        dictData: dataDictionary,
      },
    });
    // 获取ExtensionList.js 中必要的下拉list
    this.props.dispatch({
      type: 'productManageM/tradingInformationDrop',
      payload: {},
    });
    if (!sessionStorage.getItem('productManage')) {
      console.log('**************非用户视图跳转进入*********');
      this.initTable(1, 10, this.state.searchParam);
    }

    window.addEventListener('resize', this.windowChange);
  }

  UNSAFE_componentWillReceiveProps(nextPorps) {
    if (nextPorps.type == 'change') {
      this.setState({
        parentRefsWidth: this.parentRefs.offsetWidth,
      });
    }
    // 从用户视图 跳转过来
    const data = sessionStorage.getItem('productManage');
    sessionStorage.removeItem('productManage');
    if (data) {
      if (this.state.pageStatus == 2) this.setState({ pageStatus: 1 });
      const obj = JSON.parse(data);
      console.log(obj, '********************');
      // 查询变量赋值 以及表单赋值
      if (obj.type == 1) {
        this.AdvancedSearchRef.props.form.resetFields();
        this.state.RANGEDATE?.setDate([undefined, undefined]);
        this.AdvancedSearchRef.props.form.setFieldsValue({
          productStatus: obj.productStatus,
          modes: ['COMMAND_MODE', 'BOOKKEEPING_MODE', 'VALUATION_BOOKKEEPING_MODEL'],
        });
        obj.modes = ['COMMAND_MODE', 'BOOKKEEPING_MODE', 'VALUATION_BOOKKEEPING_MODEL'];
        if (this.state.RANGEDATEEnd) {
          this.state.RANGEDATEEnd?.setDate([moment(obj.endDateStart), null]);
        } else {
          setTimeout(() => {
            this.state.RANGEDATEEnd?.setDate([moment(obj.endDateStart), null]);
          }, 300);
        }
        delete obj.type;
        this.setState(
          {
            sortedInfo: null,
            searchParam: { ...obj },
          },
          () => {
            // 根据特定条件查询
            this.initTable(1, 10, obj);
          },
        );
        return;
      }
      if (obj.type == 2) {
        this.AdvancedSearchRef.props.form.resetFields();
        if (this.state.RANGEDATEEnd) {
          this.state.RANGEDATEEnd?.setDate([moment(obj.endDateStart), moment(obj.endDateEnd)]);
        } else {
          setTimeout(() => {
            this.state.RANGEDATEEnd?.setDate([moment(obj.endDateStart), moment(obj.endDateEnd)]);
          }, 300);
        }
        delete obj.type;
        this.setState(
          {
            sortedInfo: {
              order: 'ascend',
              field: 'endDate',
              columnKey: 'endDate',
            },
            searchParam: { ...obj },
          },
          () => {
            // 根据特定条件查询
            this.initTable(1, 10, obj);
          },
        );
        return;
      }
      if (obj.type == 3) {
        this.AdvancedSearchRef.props.form.resetFields();
        if (this.state.RANGEDATE) {
          this.state.RANGEDATE?.setDate([moment(obj.startDateStart), moment(obj.startDateEnd)]);
        } else {
          setTimeout(() => {
            this.state.RANGEDATE?.setDate([moment(obj.startDateStart), moment(obj.startDateEnd)]);
          }, 300);
        }
        delete obj.type;
        this.setState(
          {
            sortedInfo: {
              order: 'ascend',
              field: 'startDate',
              columnKey: 'startDate',
            },
            searchParam: { ...obj },
          },
          () => {
            // 根据特定条件查询
            this.initTable(1, 10, obj);
          },
        );
      }
    }
  }

  windowChange = () => {
    // 当页面状态改变的时候
    this.setState({
      parentRefsWidth: this.parentRefs.offsetWidth,
    });
  };

  componentWillUnmount() {
    // 删除窗口大小的监听
    window.removeEventListener('resize', this.windowChange);
  }

  // 查询表格的内容
  initTable = (currentPage, numInPage, searchParam) => {
    const { sortedInfo = {} } = this.state;
    const obj = {};
    if (sortedInfo?.order) {
      (obj.columnKey = sortedInfo?.columnKey), (obj.order = sortedInfo?.order);
    }
    const params = {
      currentPage,
      numInPage,
      ...searchParam,
      ...obj,
      productStatus: searchParam?.productStatus?.join(','),
    };
    this.props.dispatch({
      type: 'productManageM/getList',
      payload: {
        ...params,
      },
      callback: (res) => {
        console.log('res', res);
        if (res) {
          this.setState({
            dataSource: res.dataSource,
            pageInfo: {
              numInPage: res.pageInfo.numInPage,
              currentPage: res.pageInfo.currentPage,
              total: res.pageInfo.total,
            },
          });
        }
      },
    });
  };

  // 查询
  onQuery = (e) => {
    if (Object.keys(e).length == 1 && Object.keys(e)[0] == 'codeId') {
      // 产品名称精准查询时清空其他查询条件
      this.state.RANGEDATE.reset();
      this.state.RANGEDATEEnd.reset();
    }
    if (e?.startDateEnd) {
      e.startDateEnd = moment(e.startDateEnd).format('YYYY-MM-DD');
    }
    if (e?.endDateEnd) {
      e.endDateEnd = moment(e.endDateEnd).format('YYYY-MM-DD');
    }
    if (e?.startDateStart) {
      e.startDateStart = moment(e.startDateStart).format('YYYY-MM-DD');
    }
    if (e?.endDateStart) {
      e.endDateStart = moment(e.endDateStart).format('YYYY-MM-DD');
    }
    this.setState(
      {
        searchParam: e,
        isReset: false,
      },
      () => {
        this.initTable(1, 10, this.state.searchParam);
      },
    );
  };

  // 重置
  onClear = () => {
    this.setState({
      sortedInfo: null, // 排序对象
      isReset: true,
    });
  };

  // 表格改变
  changeTable = (pagination, filters, sorter) => {
    this.setState(
      {
        sortedInfo: sorter,
      },
      () => {
        if (this.state.isReset) {
          message.warning('表格已重置，请重新查询!');
        } else {
          this.initTable(pagination.current, pagination.pageSize, this.state.searchParam);
        }
      },
    );
  };

  // 新增按钮
  add = () => {
    // 点击新增进入表单页面 且pageType此时是add
    this.setState({
      pageStatus: '2',
      pageType: 'add',
      modeType: '0',
      formDatas: {
        baseInfo: {}, // 基本信息
        beiAnInfo: {}, // 备案信息
        publishInfo: {}, // 发行信息
      },
      beiAnSendPublish: null,
    });
  };

  // 处理编辑查看的情况
  handleFn = (id, type) => {
    this.getDetailView(id, type);
  };

  // 初始化进入进行请求获取三个tab中信息内容
  getDetailView = (id, type) => {
    this.props.dispatch({
      type: 'productManageM/getDetail',
      payload: {
        id,
        // type:type
      },
      callback: (res) => {
        if (res) {
          this.setState({
            pageStatus: '2',
            pageType: type,
            productId: id,
            modeType: res?.baseInfo?.modetype,
            formDatas: {
              baseInfo: res?.baseInfo || {}, // 基本信息
              temp: new Date().getTime(),
            },
          });
        }
      },
    });
  };

  // 处理删除的情况
  handleDel = (id) => {
    this.props.dispatch({
      type: 'productManageM/deleteForm',
      payload: {
        id,
      },
      callback: (res) => {
        if (res) {
          message.success('删除成功！');
          // 删除后重新进行查询
          this.initTable(1, 10, this.state.searchParam);
        }
      },
    });
  };

  // 打开负载端维护列表弹窗
  openModal = (record) => {
    this.queryPortfolioList(record?.gzCode);
    this.setState({
      visible: true,
      record,
    });
  };

  // 获取组合代码下拉列表
  queryPortfolioList = (code) => {
    // 设置了产品code时，获取产品下的组合
    this.props.dispatch({
      type: 'productAGroupM/getProductGroup',
      payload: {
        authority: 'read',
        maatApi: !!isZiGuanEvir(),
        productCode: code,
      },
      callback: () => {},
    });
  };

  // 关闭负载端维护列表弹窗
  closeModal = () => {
    this.setState({
      visible: false,
      record: undefined,
    });
  };

  // 处理列
  handleColumns = (columns) => {
    console.log('column', columns);
    const { productManageM } = this.props;
    const { dictMapSelect, TransactionMode } = productManageM;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    const isOperate = getUserInfo().isSuper || getUserInfo().isTenantAdmin;
    const list = [];
    for (const item in TransactionMode) {
      const newItem = {};
      newItem.value = item;
      newItem.title = TransactionMode[item];
      list.push(newItem);
    }
    if (columns && columns.length) {
      if (columns[columns.length - 1].title != '操作') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          fixed: 'right',
          width: 220,
          operates: isOperate
            ? [
                {
                  title: '负债端维护',
                  onClick: (record, index) => {
                    this.openModal(record);
                  },
                },
                {
                  title: '查看',
                  onClick: (record, index) => {
                    this.handleFn(record.id, 'view');
                  },
                },
                {
                  title: '编辑',
                  onClick: (record, index) => {
                    this.handleFn(record.id, 'edit');
                  },
                },
                {
                  title: '删除',
                  onClick: (record, index) => {
                    this.handleDel(record.id);
                  },
                },
              ]
            : [
                {
                  title: '负债端维护',
                  onClick: (record, index) => {
                    this.openModal(record);
                  },
                  rules: {
                    hide: { relation: 'and', items: [{ key: 'flag', value: [true], relation: ['!='] }] },
                  },
                },
                {
                  title: '查看',
                  onClick: (record, index) => {
                    this.handleFn(record.id, 'view');
                  },
                },
                {
                  title: '编辑',
                  onClick: (record, index) => {
                    this.handleFn(record.id, 'edit');
                  },
                  rules: {
                    hide: { relation: 'and', items: [{ key: 'flag', value: [true], relation: ['!='] }] },
                  },
                },
                {
                  title: '删除',
                  onClick: (record, index) => {
                    this.handleDel(record.id);
                  },
                  rules: {
                    hide: { relation: 'and', items: [{ key: 'flag', value: [true], relation: ['!='] }] },
                  },
                },
              ],
        });
      }
      if (columns.length) {
        columns.map((item, index) => {
          if (
            item.key == 'productType' ||
            item.key == 'inveType' ||
            item.key == 'code' ||
            item.key == 'startDate' ||
            item.key == 'endDate' ||
            item.key === 'baxx_cpmjfs' ||
            item.key === 'limits' ||
            item.key === 'productWorkType'
          ) {
            item.sorter = true;
            item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
          }
          if (item.key == 'productStatus') {
            item.width = 90;
            item.render = (text, record) => {
              const arrs = dictMapSelect.BAXX_CPZT && dictMapSelect.BAXX_CPZT.filter((item) => item.value == text);
              return (arrs?.length && arrs[0].title) || (text ? text : '--');
            };
          } else if (item.key == 'productType') {
            item.render = (text, record) => {
              const arrs = dictMapSelect.MAAT_PRODUCT_TYPE && dictMapSelect.MAAT_PRODUCT_TYPE.filter((item) => item.value == text);
              return (arrs?.length && arrs[0].title) || (text ? text : '--');
            };
            item.width = 100;
          } else if (item.key == 'inveType') {
            item.render = (text, record) => {
              const arrs = dictMapSelect.BAXX_TZLX && dictMapSelect.BAXX_TZLX.filter((item) => item.value == text);
              return (arrs?.length && arrs[0].title) || (text ? text : '--');
            };
            item.width = 100;
          } else if (item.key == 'baxx_cpmjfs') {
            item.render = (text, record) => {
              const arrs = dictMapSelect.BAXX_CPMJFS && dictMapSelect.BAXX_CPMJFS.filter((item) => item.value == text);
              return (arrs?.length && arrs[0].title) || (text ? text : '--');
            };
            item.width = 160;
          } else if (item.key == 'limits') {
            item.render = (text, record) => {
              const arrs = dictMapSelect.ZGTZPT_PRODUCY_INFO_LIMIT && dictMapSelect.ZGTZPT_PRODUCY_INFO_LIMIT.filter((item) => item.value == text);
              return (arrs?.length && arrs[0].title) || (text ? text : '--');
            };
            item.width = 160;
          } else if (item.key == 'productWorkType') {
            item.render = (text, record) => {
              const arrs = dictMapSelect.BAXX_CPYZMS && dictMapSelect.BAXX_CPYZMS.filter((item) => item.value == text);
              return (arrs?.length && arrs[0].title) || (text ? text : '--');
            };
            item.width = 160;
          } else if (item.key == 'productName') {
            item.fixed = 'left';
            item.type = 'maxContent';
            item.width = 160;
          } else if (item.key == 'startDate' || item.key == 'endDate') {
            item.type = 'date';
          } else if (item.key == 'productSimpleName' || item.key == 'code') {
            item.width = 160;
          }
          // 交易模式
          if (item.key == 'modes') {
            item.render = (text, record) => {
              return findTitleByValue(text, list);
            };
            item.width = 160;
          }
        });
      }
    }
  };

  // 跳转到产品组定义页面
  changeRouterPG = () => {
    this.props.dispatch(routerRedux.push(`/SystemManagement/productGroupDefinition`));
  };

  // 跳转到组合定义页面
  changeRouterG = () => {
    this.props.dispatch(routerRedux.push(`/SystemManagement/portfolioTreeMnt`));
  };

  render() {
    const _this = this;
    const { columns, dataSource, pageInfo, pageStatus, pageType, productId, formDatas, parentRefsWidth, modeType } = this.state;
    const { productManageM, loading } = this.props;
    const { dictMapSelect, isRefresh, TransactionMode } = productManageM;
    const list = [];
    for (const item in TransactionMode) {
      const newItem = {};
      newItem.value = item;
      newItem.title = TransactionMode[item];
      list.push(newItem);
    }
    const datasSource = [
      {
        dataIndex: ['codeId', 'productName'],
        title: '产品名称',
        type: DATA_ENTRY.SEARCHANDSELECTC,
        codeType: config.cpgl,
      },
      {
        dataIndex: ['startDateStart', 'startDateEnd'],
        title: '起始日区间',
        type: DATA_ENTRY.RANGEDATE,
        initialValue: [null, null],
        onRef: (ref) => this.setState({ RANGEDATE: ref }),
        disableFuture: false,
        allowClear: true,
      },
      {
        dataIndex: ['endDateStart', 'endDateEnd'],
        title: '到期日区间',
        type: DATA_ENTRY.RANGEDATE,
        initialValue: [null, null],
        onRef: (ref) => this.setState({ RANGEDATEEnd: ref }),
        disableFuture: false,
        allowClear: true,
      },
      {
        dataIndex: 'productStatus',
        title: '产品状态',
        type: DATA_ENTRY.SELECT,
        dataSource: dictMapSelect.BAXX_CPZT,
        allowClear: true,
        showSearch: false,
        isMultiple: true,
      },
      {
        dataIndex: 'modes',
        title: '交易模式',
        type: DATA_ENTRY.SELECT,
        dataSource: list || [],
        allowClear: true,
        isMultiple: true,
      },
    ];
    this.handleColumns(columns);
    if (isRefresh) {
      this.props
        .dispatch({
          type: 'productManageM/changeRresh',
          payload: {
            status: false,
          },
        })
        .then(() => {
          if (this.state.pageType == 'add') this.AdvancedSearchRef.props.form.resetFields();
          this.setState(
            {
              searchParam: this.state.pageType == 'edit' ? { ...this.state.searchParam } : {},
            },
            () => {
              this.initTable(1, 10, this.state.searchParam);
            },
          );
        });
    }
    return (
      <ContentPackage
        title='产品管理'
        contentHtml={
          <div ref={(ref) => (this.parentRefs = ref)}>
            <div style={{ display: pageStatus == '1' ? 'inherit' : 'none' }}>
              <div>
                <AdvancedSearch onRef={(ref) => (this.AdvancedSearchRef = ref)} dataSource={datasSource} onQuery={this.onQuery} onClear={this.onClear} />
              </div>
              <div className={styles.productButton}>
                <PrimaryC title='新增' onClick={this.add} style={{ marginTop: '20px', marginBottom: '16px' }} />
                <div className={styles.productSet}>
                  <PrimaryC
                    title='产品组设置'
                    style={{ marginTop: '20px', marginBottom: '16px' }}
                    helper='多个产品向上组合'
                    onClick={() => {
                      this.changeRouterPG();
                    }}
                  />
                  <PrimaryC
                    title='组合设置'
                    style={{ marginTop: '20px', marginBottom: '16px', marginLeft: '20px' }}
                    helper='单个产品向下拆分'
                    onClick={() => {
                      this.changeRouterG();
                    }}
                  />
                </div>
              </div>
              <TableC
                columns={columns}
                dataSource={dataSource}
                loading={loading}
                total={pageInfo.total}
                scroll={{ x: 'max-content' }}
                pageSize={pageInfo.numInPage}
                current={pageInfo.currentPage}
                selfScrollY={true}
                onChange={this.changeTable}
                rowKey='id'
              />
            </div>
            {pageStatus == '2' && (
              <div>
                <BaseInfoForm
                  widthSet={parentRefsWidth}
                  formDatas={formDatas}
                  pageType={pageType}
                  pageStatus={pageStatus}
                  mainThis={_this}
                  productId={productId}
                  modeType={modeType}
                />
              </div>
            )}
            {this.state.visible && <MyModalC visible={this.state.visible} detailData={this.state.record || {}} onCancel={this.closeModal} />}
          </div>
        }
      />
    );
  }
}
export default connect(({ productManageM, productAGroupM, loading, globalM }) => ({
  productManageM,
  productAGroupM,
  loading: loading.effects['productManageM/getList'],
  globalM,
}))(ProductManage);
